package Stack.Stack;

import java.util.Iterator;

/*
    使用链表实现栈
 */
public class Stack<T> implements Iterable<T> {

    private class Node<T> {
        T item;
        Node<T> next;

        public Node(T item, Node<T> next) {
            this.item = item;
            this.next = next;
        }
    }

    private Node<T> head;
    private int N;

    public Stack() {
        head = new Node<>(null, null);
        N = 0;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }

    public T pop() {
        Node<T> current = head.next;
        if (current != null) {//安全性检测，防止链表为空时出现 NullPointerException
            //current 不为空，说明栈中至少还有一个元素
            //栈中无元素则栈为 head -> null
            head.next = current.next;
        }
        N--;
        return current.item;
    }

    public void push(T t) {
        Node<T> n = new Node<>(t, null);
        n.next = head.next;
        head.next = n;
        N++;
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            Node<T> n = head;

            @Override
            public boolean hasNext() {
                return n.next != null;
            }

            @Override
            public T next() {
                n = n.next;
                return n.item;
            }
        };
    }
}
